import {defineStore} from 'pinia';
import {LoginStoreActions, LoginStoreState, UserMenus} from "@/store/login/types";
import {ACCOUNT_LOGIN, GET_USER_PRINCIPAL, QUERY_MY_MENU, REFRESH_TOKEN} from "@/apis/login-apis";
import cacheFactory, {CacheType} from "@/utils/cache/cache-factory";
import router from "@/configs/routers/routers";
import {mapMenusToRoutesAndPermissions} from "@/utils/map-menus";

const loginStore = defineStore<string, LoginStoreState, any, LoginStoreActions>("loginStore", {
    state: (): LoginStoreState => {
        return {
            tokenInfo: {},
            userInfo: {},
            userMenus: [],
            permission: [],
            isRefresh: false
        }
    },
    getters: {},
    actions: {
        async accountLogin(account): Promise<any> {
            console.log("login store start...")
            console.log(account)
            const loginResult = await ACCOUNT_LOGIN({
                username: account.username,
                pwd: account.password
            })
            this.tokenInfo = {...loginResult.data}
            cacheFactory.instance(CacheType.LOCAL_STORAGE)?.setCache("tokenInfo", this.tokenInfo)
            await this.queryUserPrincipal()
            await this.queryMyMenu()
            router.push({
                path: "/"
            })
        },
        mobileLogin(params): void {
            console.log("手机号登陆");
        },
        async queryUserPrincipal() {
            // 获得登陆用户信息
            const userPrincipal = await GET_USER_PRINCIPAL();
            if (userPrincipal){
                this.userInfo = {...userPrincipal.data}
            }

            cacheFactory.instance(CacheType.LOCAL_STORAGE)?.setCache("userInfo", this.userInfo)
        },

        async queryMyMenu() {
            const myMenuResult = await QUERY_MY_MENU();
            this.userMenus = [...myMenuResult.data]

            const routerResult = await mapMenusToRoutesAndPermissions(this.userMenus);
            console.log(routerResult.permissions, routerResult.routes)
            this.permission = routerResult.permissions;
            routerResult.routes.forEach(route => router.addRoute("Home", route))
            cacheFactory.instance(CacheType.LOCAL_STORAGE)?.setCache("userMenus", this.userMenus);
        },
        async loadFromLocal() {
            const tokenInfo = cacheFactory.instance(CacheType.LOCAL_STORAGE)?.getCache("tokenInfo");
            if (tokenInfo) {
                this.tokenInfo = tokenInfo;
            }
            const userMenus = cacheFactory.instance(CacheType.LOCAL_STORAGE)?.getCache("userMenus");
            if (userMenus){
                this.userMenus = userMenus;
                const routerResult = await mapMenusToRoutesAndPermissions(this.userMenus);
                console.log(routerResult.permissions, routerResult.routes)
                this.permission = routerResult.permissions;
                routerResult.routes.forEach(route => router.addRoute("Home", route))
            }
            const userInfo = cacheFactory.instance(CacheType.LOCAL_STORAGE)?.getCache("userInfo");
            if (userInfo){
                this.userInfo = userInfo;
                await this.queryUserPrincipal();
            }
        },
        async refreshToken() {
            console.log("刷新token")
            const refreshResult = await REFRESH_TOKEN(this.tokenInfo?.refreshToken)
            this.tokenInfo = {...refreshResult.data}
            cacheFactory.instance(CacheType.LOCAL_STORAGE)?.setCache("tokenInfo", this.tokenInfo)
            await this.queryUserPrincipal()
            await this.queryMyMenu()
            return Promise.resolve()
        },
    }
})

export default loginStore

export const setupStore = async () => {
    const store = loginStore()
    await store.loadFromLocal()
    store.isRefresh = true;
    return Promise.resolve("true")
}
